package cn.mifengkong.appcommon.util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;

import java.io.File;

/**
 * Created by jiangyongxing on 2018/1/13.
 * 描述：
 */

public class CameraUtil {

    public static final int REQUESTCODE_PICK = 100;        // 相册选图标记
    public static final int REQUESTCODE_TAKE = 101;        // 相机拍照标记
    public static final int REQUESTCODE_CUTTING = 102;    // 图片裁切标记

    private static final String IMAGE_FILE_NAME = "avatarImage.jpg";// 头像文件名称
    private static Uri uritempFile;

    public static void openSystemCamera(Activity activity) {
        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        takeIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        //下面这句指定调用相机拍照后的照片存储的路径
        File file = new File(activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), IMAGE_FILE_NAME);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        } else {
            Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", file);
            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        activity.startActivityForResult(takeIntent, REQUESTCODE_TAKE);
    }

    public static void openAlbum(Activity activity) {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        // 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        activity.startActivityForResult(pickIntent, REQUESTCODE_PICK);
    }

    public static void onActivityResultWithPhotoZoom(Activity activity, int requestCode, int resultCode, Intent data, ImageCroppedCallBack callBack) {
        if (Activity.RESULT_OK != resultCode) {
            return;
        }
        switch (requestCode) {

            case REQUESTCODE_PICK:// 直接从相册获取
                try {
                    startPhotoZoom(activity, data.getData());
                } catch (NullPointerException e) {
                    e.printStackTrace();// 用户点击取消操作
                }
                break;
            case REQUESTCODE_TAKE:// 调用相机拍照
                File temp = new File(activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), IMAGE_FILE_NAME);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    startPhotoZoom(activity, Uri.fromFile(temp));
                } else {
                    Uri uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileprovider", temp);
                    startPhotoZoom(activity, uri);
                }
                break;
            case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                if (data != null) {
                }
                returnResultPic(activity, callBack);
                break;
            default:
                break;
        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param activity
     * @param callBack
     */
    public static void returnResultPic(Activity activity, ImageCroppedCallBack callBack) {
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(uritempFile));
            if (callBack != null) {
                callBack.mageiCroppedSuccessfully(bitmap);
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + IMAGE_FILE_NAME);
                if (file.exists()) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public static void startPhotoZoom(Activity activity, Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + IMAGE_FILE_NAME);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        activity.startActivityForResult(intent, REQUESTCODE_CUTTING);
    }


    public interface ImageCroppedCallBack {
        void mageiCroppedSuccessfully(Bitmap bitmap);
    }
}
